package com.gzsxy.esjy.service.netty.client;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 客户端通道管理（暂无用）
 * @author zhangxiaolong
 * @date 2022/7/11 9:36
 */
public class ChannelManager {
	
	private final static Map<String,Set<Channel>> CHANNEL_CLIENTS = new ConcurrentHashMap<String,Set<Channel>>() ;
	
	private final static ChannelFutureListener remover = future -> {
		TransChannelHandler transChannelHandler = future.channel().pipeline().get(TransChannelHandler.class);
		if(transChannelHandler != null) {
			String tag = transChannelHandler.getTag();
			operateChannel(tag, future.channel(), true) ;
		}
	};
	
	
	public static void addListener(Channel channel) {
		channel.closeFuture().addListener(remover);
	}
	
	/**
	 * 操作channel
	 * @param key
	 * @param channel !=null,移除指定Channel
	 * @param flag true:获取(移除) false:放置
	 * @return
	 */
	public static Channel operateChannel(String key,Channel channel,boolean flag) {
		synchronized (key.intern()) {
			Set<Channel> set = CHANNEL_CLIENTS.get(key);
			if(set == null) {
				set = new HashSet<Channel>() ;
				CHANNEL_CLIENTS.put(key, set) ;
			}
			if(flag) {
				if(channel != null) {
					set.remove(channel) ;
					return channel ;
				}
				//获取channel
				Iterator<Channel> iterator = set.iterator();
				if(iterator.hasNext()) {
					Channel next = iterator.next();
					set.remove(next) ;
					return next;
				}
				return null ;
			}else {
				set.add(channel);
				return channel ;
			}
		}
	}
}
